import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from './auth'
import router from '@/router'
// import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj',
  timeout: 5000
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers.Authorization = `Bearer ${getToken()}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    return response.data
  }, error => {
    // 错误统一处理
    if (error.response.status === 401) {
      Message.error('用户登录信息过期，请重新登录')
      store.dispatch('user/logout')
      router.replace('/login')
    } else {
      Message.error(error.response.data.msg)
    }
    return Promise.reject(error)
  }
)

export default service
